package com.hzit.auth.service.impl;

import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hzit.auth.mapper.UserMapper;
import com.hzit.auth.service.IPermissionService;
import com.hzit.auth.service.IUserService;
import com.hzit.auth.vo.UserVo;
import com.hzit.entity.LoginUser;
import com.hzit.entity.Permission;
import com.hzit.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;

/**
 * 类名：
 * 作者：WF
 * 功能：
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
	@Autowired
	private IPermissionService permissionService;

	//1. 根据用户名查询用户是否存在
	@Override
	public LoginUser findUser(UserVo vo) {
		LoginUser loginUser = new LoginUser();
		//1.0 生成一个token值
		String token = UUID.randomUUID().toString();
		loginUser.setToken(token);
		//1.1 根据用户名查询用户对象
		User user = this.getOne(new QueryWrapper<User>().eq("username", vo.getUsername()));

		///////////////////////////// 查询当前登录用户的权限与角色列表  /////////////////////////////
		//1.1 获取用户id
		String id = user.getId();
		//1.2 获取当前用户的权限列表
		List<String> permissions = permissionService.selectPermissionValueByUserId(id);
		//1.3 添加到当前登录用户上
		loginUser.setPermissions(permissions);

		//1.2 对vo中的密码（表单传入）进行加密
		String pwd = SecureUtil.md5(vo.getPassword());
		//1.3 比较与数据库是否一致
		if (pwd.equals(user.getPassword())) {
			loginUser.setUser(user);
			return loginUser;
		}
		return null;
	}
}
